<template>
  <view class="container">
    <view class="section">
      <text class="title">明天天气预报</text>
      <button @click="getWeather" type="primary" class="btn">获取天气预报</button>
      <view class="weather-card" v-if="tomorrowWeather">
        <text class="weather-item">日期：{{ tomorrowWeather.date }}</text>
        <text class="weather-item">星期：{{ tomorrowWeather.week }}</text>
        <text class="weather-item">最高温：{{ tomorrowWeather.high }}℃</text>
        <text class="weather-item">最低温：{{ tomorrowWeather.low }}℃</text>
      </view>
      <text class="tip" v-if="weatherTip">{{ weatherTip }}</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      tomorrowWeather: null,
      weatherTip: '',
      weatherApiUrl: 'http://t.weather.sojson.com/api/weather/city/101230501'
    };
  },
  methods: {
    getWeather() {
      this.weatherTip = '正在获取天气预报...';
      uni.request({
        url: this.weatherApiUrl,
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data.status === 200) {
            const tomorrowData = res.data.data.forecast[1];
            this.tomorrowWeather = {
              date: tomorrowData.date,
              week: tomorrowData.week,
              high: tomorrowData.high.replace('高温', '').replace('℃', ''),
              low: tomorrowData.low.replace('低温', '').replace('℃', '')
            };
            this.weatherTip = '';
          } else {
            this.weatherTip = '天气预报获取失败，请重试';
            console.error('天气预报接口返回异常：', res.data);
          }
        },
        fail: (err) => {
          this.weatherTip = '网络错误，无法获取天气预报';
          console.error('天气预报请求失败：', err);
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
}
.section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}
.title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  display: block;
}
.btn {
  margin-bottom: 20rpx;
}
.weather-card {
  margin-top: 20rpx;
  background-color: #f8f9fa;
  padding: 20rpx;
  border-radius: 8rpx;
}
.weather-item {
  display: block;
  font-size: 28rpx;
  margin-bottom: 10rpx;
}
.tip {
  font-size: 28rpx;
  color: #ff4d4f;
  margin-top: 20rpx;
}
</style>